/*
 * Heap.h
 *
 *  Created on: 13-Nov-2009
 *
 */

#ifndef HEAP2_H
#define HEAP2_H

#include "../common.h"
#include "../BufferManager/BufferManager.h"
#include <vector>

#define NEW 0
#define EXISTING 1

#define HEAD_PAGE 2

#define MAX_FREE_SPACE (PAGE_SIZE - (sizeof(int) +sizeof(Heap2::sde)))

#define MAX_NOS_DES ((PAGE_SIZE-sizeof(dpageheader))/sizeof(de))

#define DBHEADER_SIZE sizeof(dp)
	typedef struct record_struct{
					unsigned char *rec;
					unsigned int recLen;
					yadbms_common::rid rid;
				}record;

class Heap2{
	typedef yadbms_common::rid RID;

	typedef struct diskptrstruct{
		long ptr;
	}dp;

	typedef struct dbheader_struct {
		dp systable;
		dp syscols;
		dp sysindex;
		char junk[PAGE_SIZE - (3*sizeof(dp))];
	}dbheader;

	typedef struct de_struct{
		dp page;
		int freespace;
	}de;

	typedef struct dpage_header_struct {
		dp next;
		int maxfreespace;
	}dpageheader;

	typedef struct dpage_struct {
		dpageheader header;
		de des[MAX_NOS_DES];
	}dpage;

	typedef struct sde_struct{
		int offset;
		int size;
	}sde;

	typedef struct sd_struct{
		sde* slots;
		int nos_slot;
	}sd;


	typedef struct dbpage_struct{
		dp parent;
		unsigned char* data;
		sd slotdir;
	}dbpage;

	//vector<record*>resultset;

//	BufferManager *buffer;

	void init(int dphfile);


//	Database *database;

	Page* getPagePtr(dp page);

	Page* getNewPagePtr();

	Page* createDBPage(long parent);

	Page* createDPPage();

	void setPagePtr(dp page,Page* ptr);

	void writePage(long pageno,Page* page);

	void unPinPage(long pageno);





public:



	Status createNewDB();

	Heap2(int dphfile);

	// return number of records in file
	int getRecCnt(int file);

	// insert record into file
	Status insertRecord(int file,unsigned char *recPtr, int recLen, RID& outRid);

	// delete record from file
	Status deleteRecord(int file,const RID& rid);

	// updates the specified record in the heapfile. returns 1 if it has to change the RID of record for update in index else returns 1
	int updateRecord(int file,RID& rid,unsigned char *recPtr, int reclen);

	// read record from file, returning pointer and length
	Status getRecord(long file,const RID& rid,unsigned char *&recPtr, int& recLen);

	// initiate a sequential scan

	int openScan(int file,vector<record> &resultset);

	// delete the file from the database
	Status deleteFile();

	//For create table, it creates new DP Page and returns its pageno
	int createHeapFile();
	Status deleteHeap(int file);
	void test();
	void set_debug();
	int heap_debug;

};


#endif

